package com.unionftech.content_login.ui.login

import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.base.IUpdate
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.common.common.bean.PhoneRegexInfo
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.ui.UFCountryCodeSelectDialogFragment
import com.unionftech.common.utils.CheckInputUtil
import com.unionftech.common.utils.ExtentUtil
import com.unionftech.content_login.R
import com.unionftech.common.R.string
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.content_login.ui.forget.UFForgetPasswordActivity

class PhoneLoginFragment : BaseFragment(), IUpdate {
    private val mEtPhone: EditText by lazy { mRootView.findViewById(R.id.et_phone) }
    private val mIvClearPhone: ImageView by lazy { mRootView.findViewById(R.id.iv_clear_phone) }
    private val mLlCountryCode: LinearLayout by lazy { mRootView.findViewById(R.id.ll_country_code) }
    private val mTvCountryCode: TextView by lazy { mRootView.findViewById(R.id.tv_country_code) }
    private val mTvPhoneError: TextView by lazy { mRootView.findViewById(R.id.tv_phone_error) }
    private lateinit var mCommonFragment: LoginCommonFragment
    private var mLoginListener: ((account: String, password: String) -> Unit)? = null
    private lateinit var mCountryInfo: CountryInfo
    private val mPhoneRegexMap = mutableMapOf<String, String>()
    private var mCountryCodeDialog: UFCountryCodeSelectDialogFragment? = null
    private var mInitPhone: String? = null
    private var mInitCountryInfo: CountryInfo? = null


    companion object {
        private const val TAG = "PhoneLoginFragment"
        private const val PARAMS_INIT_PHONE = "params_init_phone"
        private const val PARAMS_INIT_COUNTRY_INFO = "params_init_country_info"

        @JvmStatic
        fun newInstance(countryInfo: CountryInfo?, phone: String?) = PhoneLoginFragment().apply {
            arguments = Bundle().apply {
                putString(PARAMS_INIT_PHONE, phone)
                putParcelable(PARAMS_INIT_COUNTRY_INFO, countryInfo)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            mInitPhone = it.getString(PARAMS_INIT_PHONE)
            mInitCountryInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                it.getParcelable(PARAMS_INIT_COUNTRY_INFO, CountryInfo::class.java)
            } else {
                it.getParcelable(PARAMS_INIT_COUNTRY_INFO)
            }
        }
    }

    override fun inflaterContentView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_phone_login, container, false)
    }


    override fun initData() {
        super.initData()
        mCommonFragment = LoginCommonFragment.newInstance()
        mCommonFragment.setCompleteListener { result ->
            mEtPhone.clearFocus()
            if (checkInput() && result) {
                requestLogin()
            }
        }
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mEtPhone.hint = DynamicResourceManager.getString(mContext, string.phone)
    }

    private fun checkInput(): Boolean {
        val areaCode = mTvCountryCode.text.toString()
        return CheckInputUtil.checkPhoneInput(
            mEtPhone.text.toString(),
            areaCode,
            mPhoneRegexMap[areaCode] ?: "",
            mEtPhone,
            mTvPhoneError,
            string.phone_empty,
            string.phone_format_incorrect
        )
    }

    override fun setListener() {
        super.setListener()
        mLlCountryCode.setOnClickListener(this)
        mIvClearPhone.setOnClickListener(this)
        mEtPhone.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                mEtPhone.isSelected = false
                setPhoneClear(mEtPhone.text)
            } else {
                mIvClearPhone.visibility = View.GONE
                checkInput()
            }
        }
        mEtPhone.addTextChangedListener { text ->
            setPhoneClear(text)
            val enable =
                !TextUtils.isEmpty(text) && !TextUtils.isEmpty(mCommonFragment.getLoginPassword())
            mCommonFragment.setLoginEnable(enable)
        }
        mCommonFragment.setGotoForgetCallback {
            UFForgetPasswordActivity.startThis(mActivity, 1)
        }
        mCommonFragment.setPasswordChangeCallback { enable ->
            val result = enable && !TextUtils.isEmpty(mEtPhone.text)
            mCommonFragment.setLoginEnable(result)
        }
    }

    private fun setPhoneClear(text: Editable?) {
        if (TextUtils.isEmpty(text)) {
            mIvClearPhone.visibility = View.GONE
        } else {
            mIvClearPhone.visibility = View.VISIBLE
        }
    }

    fun setCountryInfo(countryInfo: CountryInfo) {
        mCountryInfo = countryInfo
        if (mInitCountryInfo != null) {
            mCountryInfo = mInitCountryInfo!!
        }
        mTvCountryCode.text = mCountryInfo.areaCode
    }

    fun setPhone(phone: String?) {
        mEtPhone.setText(phone)
        mEtPhone.clearFocus()
        mEtPhone.isSelected = false
        mTvPhoneError.visibility = View.INVISIBLE
    }

    fun resetPasswordData() {
        if (::mCommonFragment.isInitialized) {
            mCommonFragment.resetPasswordData()
        }
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        mRootView.setBackgroundColor(mContext.getColor(android.R.color.transparent))
        val transaction = childFragmentManager.beginTransaction()
        transaction.add(R.id.fl_login_common, mCommonFragment)
        transaction.commitNowAllowingStateLoss()
        childFragmentManager.executePendingTransactions()
        loadData()
    }

    override fun loadData() {
        super.loadData()
        updateAllPhoneRegex()
    }

    private fun updateAllPhoneRegex() {
        val list = GlobalInfoManager.getInstance().getAllPhoneRegex()
        if (list.isNotEmpty()) {
            mPhoneRegexMap.clear()
            for (info in list) {
                mPhoneRegexMap[info.areaCode] = info.regex
            }
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_ALL_PHONE_REGEX)
        }
    }

    private fun requestLogin() {
        val phone = mEtPhone.text.toString()
        val pwd = mCommonFragment.getLoginPassword()
        mLoginListener?.invoke(phone, pwd)
    }

    fun setLoginListener(listener: (account: String, password: String) -> Unit) {
        this.mLoginListener = listener
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.ll_country_code -> {
                gotoCountryCode()
            }

            R.id.iv_clear_phone -> {
                mEtPhone.setText("")
            }
        }
    }

    private fun gotoCountryCode() {
        if (mCountryCodeDialog == null) {
            mCountryCodeDialog = UFCountryCodeSelectDialogFragment.newInstance(mContext)
            mCountryCodeDialog!!.setCallBack { countryInfo ->
                countryInfo.also {
                    mTvCountryCode.text = it.areaCode
                    mCountryInfo = it
                    ExtentUtil.setPhoneDynamicPaddingLeft(mContext, mEtPhone, it.areaCode)
                }
            }
        }
        if (mCountryCodeDialog!!.dialog == null || !mCountryCodeDialog!!.dialog!!.isShowing) {
            mCountryCodeDialog!!.show(
                childFragmentManager, UFCountryCodeSelectDialogFragment::class.java.simpleName
            )
        }
    }

    override fun onUpdate(obj: Any?) {
        if (obj is List<*>) {
            updatePhoneRegex(obj)
        }
    }

    private fun updatePhoneRegex(list: List<*>) {
        mPhoneRegexMap.clear()
        for (info in list) {
            if (info is PhoneRegexInfo) {
                mPhoneRegexMap[info.areaCode] = info.regex
            }
        }
    }

    override fun onDestroy() {
        mCountryCodeDialog?.dismiss()
        mCountryCodeDialog?.setCallBack(null)
        mCountryCodeDialog = null
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }

}